package com.business.action.admin.system;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.business.bean.admin.DicBean;

import net.sf.rose.file.util.FileUtils;
import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.dao.BeanDAO;
import net.sf.rose.jdbc.query.BeanSQL;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.DateFormat;
import net.sf.rose.util.RoseRuntimeException;
import net.sf.rose.web.util.WebUtils;

/**
 * @author fengjian E-mail: 9110530@qq.com
 * @version 创建时间：2015年6月16日 下午8:21:49 类说明 ：字典后台管理
 */
@Controller
@RequestMapping("/admin/dic")
public class DicAction {

	/**
	 * 保存字典数据
	 * <p>
	 * 存储二份数据，js文件供前端使用，另一份保存至数据库中。
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/save.do")
	public PageBean save(Service service, String json) throws IOException {
		PageBean page = new PageBean();
		File path = WebUtils.WEB_APP_PATH;
		path = new File(path, "js");
		path = new File(path, "common");
		File file = new File(path, "constant.js");
		String time = DateFormat.format(new Date(), DateFormat.DATE_FORMAT_4);
		File old = new File(path, "constant-" + time + ".js");
		FileUtils.copy(file, old);
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			StringBuilder sb = new StringBuilder();
			// 必须是一行说明，一行键值对
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				if (tempString.trim().equals("// 以下是数据部分")) {
					sb.append(tempString);
					break;
				} else {
					sb.append(tempString).append('\n');
				}
			}
			reader.close();
			// 写文件
			List<DicBean> list = new ArrayList<>();
			BufferedWriter buf = new BufferedWriter(new FileWriter(file));
			buf.write(sb.toString());
			JSONArray array = JSON.parseArray(json);
			for (Object obj : array) {
				sb = new StringBuilder();
				JSONObject js = (JSONObject) obj;
				sb.append('\n');
				sb.append("\t this.").append(js.getString("tableName")).append(" = {\n");// ,
				sb.append("\t\ttitle: '").append(js.getString("tableTitle")).append("',\n");
				sb.append("\t\tdata: [");
				JSONArray data = js.getJSONArray("data");
				int index = 1;
				for (Object o : data) {
					JSONObject d = (JSONObject) o;
					sb.append("\n\t\t\t{id: '").append(d.getString("id"));
					sb.append("', text: '").append(d.getString("text")).append("'},");
					DicBean dic = new DicBean();
					dic.setTableName(js.getString("tableName"));
					dic.setTableTitle(js.getString("tableTitle"));
					dic.setId(d.getString("id"));
					dic.setText(d.getString("text"));
					dic.setSequence(index);
					list.add(dic);
					index++;
				}
				sb.deleteCharAt(sb.length() - 1);
				sb.append("\n\t\t]\n");
				sb.append("\t}\n");
				buf.write(sb.toString());
			}
			buf.write("}");
			buf.flush();
			buf.close();
			// 更新数据库字典表
			BeanDAO dao = new BeanDAO(service);
			BeanSQL query = dao.getQuerySQL();
			// 清空表数据
			query.setSQL("delete from AD_DIC");
			dao.update();
			// 添加全新的字典数据
			query.createBatchInsertSql(list);
			dao.batchUpdate();
		} catch (Exception e) {
			throw new RoseRuntimeException(e);
		}
		return page;
	}

}
